<template>
    <section class="page-wrap">
        <div class="head-notice" v-if="noticeForm && noticeForm.location == 'top' && isShowNotice">
            <svg-icon name="icon_notice" style="width: 20px;height: 20px;color: #0077FF;margin-right: 8px;" />
            {{ noticeForm.content }}

            <svg-icon @click="isShowNotice = false" name="icon_close"
                style="width: 12px;height: 12px;color: #333333;margin-left: auto;" />
        </div>

        <a-modal v-model:visible="open" title="通知" @ok="handleOk" width="1000px">
            <div v-html="noticeForm.content" class="modal-wrap"></div>
        </a-modal>

        <XsyModal v-model="open" :text="noticeForm.content"></XsyModal>

        <a-spin :spinning="loading">
            <div>
                <div class="page-header">
                    <div class="flex">
                        <a-dropdown :trigger="['click']" class="">
                            <template #overlay>
                                <a-menu @click="onCreatInstance">
                                    <a-menu-item key="communityCloud">
                                        <a-button type="link">社区云</a-button>
                                    </a-menu-item>
                                    <a-menu-item key="highlyAvailableCloud">
                                        <a-button type="link">高可用云</a-button>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                            <a-button type="primary" style="display: flex;align-items: center;">
                                <template #icon>
                                    <svg-icon name="icon_add" style="width:16px;height:16px;margin-right: 6px;" />
                                </template>
                                创建实例
                            </a-button>
                        </a-dropdown>

                        <a-space>
                            <a-select ref="select" :bordered="false" v-model:value="form.type" placeholder="全部算力类型"
                                allowClear style="width: 160px" class="icon-select region" @change="getList">
                                <a-select-option value="1">社区云</a-select-option>
                                <a-select-option value="2">高可用云</a-select-option>
                            </a-select>

                            <a-select ref="select" :bordered="false" v-model:value="form.stype" placeholder="全部计费模式"
                                allowClear style="width: 160px" class="icon-select stype" @change="getList">
                                <a-select-option value="payg">按量计费</a-select-option>
                                <a-select-option value="monthly">包月</a-select-option>
                                <a-select-option value="weekly">包周</a-select-option>
                                <a-select-option value="daily">包天</a-select-option>
                                <a-select-option value="bidding">竞价计费</a-select-option>
                                <a-select-option value="card_less">无卡启动</a-select-option>
                            </a-select>

                            <a-select ref="select" :bordered="false" v-model:value="form.status" placeholder="全部状态"
                                allowClear style="width: 160px" class="icon-select status" @change="getList">
                                <a-select-option value="running">运行中</a-select-option>
                                <a-select-option value="stopd">已关机</a-select-option>
                                <a-select-option value="handling">执行中</a-select-option>
                                <a-select-option value="failed">失败</a-select-option>
                            </a-select>
                        </a-space>
                    </div>

                    <div class="flex">
                        <div style="font-size: 14px;color: #0077FF;display: flex;align-items: center;margin-right: 24px;cursor: pointer;"
                            @click="openImageDocs('/docs/help_document/practice/baidupcs')">
                            <QuestionCircleOutlined style="margin:0 8px 0 0;color: #D7D9DD;" />如何传数据
                        </div>

                        <a-input-search v-model:value="form.search" placeholder="请输入实例名称/实例ID" style="width: 200px"
                            @search="getList" />
                    </div>

                </div>

                <div class="card-title">
                    <a-row>
                        <a-col :span="5" class="page-txt">地区/实例</a-col>
                        <a-col :span="4" class="page-txt">实例详情</a-col>
                        <a-col :span="4" class="page-txt">系统盘</a-col>
                        <a-col :span="4" class="page-txt">数据盘</a-col>
                        <a-col :span="4" class="page-txt">镜像</a-col>
                        <a-col :span="3" class="page-txt">状态</a-col>
                    </a-row>
                </div>

                <div v-if="tableList.length">
                    <div class="instance-cards" v-for="(item, index) in tableList" :key="item?.Instance?.instanceId">
                        <a-card>
                            <div>
                                <a-row>
                                    <a-col :span="5">
                                        <p class="mb-8">{{ item?.MachineBaseInfo?.regionName }} {{ item?.Instance?.name
                                        }}<svg-icon name="icon_edit" style="width: 16px;height: 16px;margin-left: 8px;"
                                                @click="openChangeInstance(item)"></svg-icon></p>
                                        <p class="page-txt">ID：{{ item?.Instance?.instanceId }}
                                            <a-button type="link" @click="onCopy(item?.Instance?.instanceId)">
                                                <template #icon>
                                                    <CopyOutlined />
                                                </template>
                                            </a-button>
                                        </p>
                                    </a-col>
                                    <a-col :span="4">
                                        <p class="mb-8">{{ item?.Instance?.gpuName }}</p>
                                        <p class="page-txt">{{ item?.GpuInfo?.humanizeMem || 0 }}GB * {{
                                            item?.Instance?.gpuNum }}
                                            卡
                                        </p>
                                    </a-col>
                                    <a-col :span="4">
                                        <div style="padding-right:32px;">
                                            <a-progress
                                                :percent="formatPercentage(item?.InstancePhysicalState?.systemDiskUsedSize, item?.InstancePhysicalState?.systemDiskSize)"
                                                :strokeColor="getProgressColor(item?.InstancePhysicalState?.systemDiskUsedSize, item?.InstancePhysicalState?.systemDiskSize)"
                                                size="small">
                                                <template #format="percent">
                                                    <div class="page-txt"><span style="color: #3F73F6;">{{
                                                        printSize(item?.InstancePhysicalState?.systemDiskUsedSize)
                                                    }}</span>
                                                        /
                                                        {{ printSize(item?.InstancePhysicalState?.systemDiskSize) }}
                                                    </div>
                                                </template>
                                            </a-progress>
                                        </div>
                                    </a-col>
                                    <a-col :span="4">
                                        <div style="padding-right:32px;">
                                            <a-progress
                                                :percent="formatPercentage(item?.InstancePhysicalState?.dataDiskUsedSize, item?.InstancePhysicalState?.dataDiskSize)"
                                                size="small"
                                                :strokeColor="getProgressColor(item?.InstancePhysicalState?.dataDiskUsedSize, item?.InstancePhysicalState?.dataDiskSize)">
                                                <template #format="percent">
                                                    <div class="page-txt"><span style="color: #3F73F6;">{{
                                                        printSize(item?.InstancePhysicalState?.dataDiskUsedSize)
                                                    }}</span> /
                                                        {{ printSize(item?.InstancePhysicalState?.dataDiskSize) }}
                                                    </div>
                                                </template>
                                            </a-progress>
                                        </div>
                                    </a-col>
                                    <a-col :span="4">
                                        <p class="page-txt">{{ item?.Image?.imageType == 'official' ? item?.Image?.imageId :
                                            item?.Image?.imageName }}</p>
                                    </a-col>
                                    <a-col :span="3">
                                        <div v-if="item?.Instance?.isPending">
                                            <span :class="formatColr(actionStatusEnum, item?.Instance?.action)">
                                                <svg-icon name="icon_instance_loading"
                                                    style="width:12px;height:12px;margin-right: 5px;"
                                                    v-if="item?.Instance?.isPending == 1" />
                                                {{ selectDictLabel(actionStatusEnum, item?.Instance?.action) }}中
                                            </span>
                                        </div>
                                        <div v-else>
                                            <span class="warning"
                                                v-if="item?.Instance?.ioStatus == 3">
                                                <svg-icon name="icon_instance_loading"
                                                    style="width:12px;height:12px;margin-right: 5px;"
                                                    v-if="item?.Instance?.isPending == 1" />
                                                {{ selectDictLabel(actionStatusEnum, item?.Instance?.action) }}失败
                                            </span>

                                            <span :class="formatColr(instanceStatusEnum, item?.Instance?.status)" v-else>
                                                <svg-icon name="icon_instance_loading"
                                                    style="width:12px;height:12px;margin-right: 5px;"
                                                    v-if="item?.Instance?.isPending == 1" />
                                                {{ selectDictLabel(instanceStatusEnum, item?.Instance?.status) }}
                                            </span>
                                        </div>
                                        <!-- 关机的时候展示gpu资源 -->
                                        <div v-if="item?.Instance?.status == 'stopd'" style="margin-top:8px;">
                                            <div style="color: #53C41B;font-size: 12px;"
                                                v-if="item?.MachineResource?.gpuNum - item?.MachineResource?.gpuNumUsed > 0">
                                                <CheckCircleFilled style="margin-right:2px;" />GPU资源充足
                                            </div>
                                            <div style=" color: #FF3D00;font-size: 12px;" v-else>
                                                <InfoCircleFilled style="margin-right:2px;" />GPU资源不足
                                            </div>
                                        </div>
                                    </a-col>
                                </a-row>
                            </div>

                            <div class="list-expand" v-if="currentIndex.indexOf(index) != -1">
                                <div>数据中心:{{ item?.MachineBaseInfo?.dcName }}</div>
                                <div class="machine-date">
                                    <div v-if="!['card_less', 'free', 'payg'].includes(item?.Instance?.skuName)">到期时间：{{
                                        item?.OrderInstance?.endTime }}</div>
                                    <div
                                        v-if="['card_less', 'free', 'payg'].includes(item?.Instance?.skuName) && item?.Instance?.scheduleStopTime">
                                        定时关机时间：{{
                                            item?.Instance?.scheduleStopTime }}</div>
                                    <div>最近开机时间：{{ item?.Instance?.lastStartTime }}</div>
                                    <div>机器可租至：{{ item?.Instance?.rentEndTime }}</div>
                                </div>
                            </div>

                            <div class="list-bottom flex">
                                <div class="flex">
                                    <div class="tags" style="background: #FFF7EC;color: #FFB138;"
                                        v-if="item?.Instance?.type == 2">
                                        <svg-icon name="pro_ cloud_b" class="tag-icon" />高可用
                                    </div>
                                    <div class="tags" style="background: #53C41B;color: #EFFAEA;"
                                        v-if="item?.Instance?.type == 1">
                                        <svg-icon name="ord_cloud_d " class="tag-icon" />社区云
                                    </div>

                                    <div class="tags" style="background: #DDDFFD; color: #5D64F7;"
                                        v-if="['card_less', 'free', 'payg'].includes(item?.Instance?.skuName)"><svg-icon
                                            name="number_a" class="tag-icon" />{{ payType[item?.Instance?.skuName] }}</div>
                                    <div class="tags" style="background: #E9FCFF; color: #24E5FF;"
                                        v-if="item?.Instance?.skuName == 'bidding'"><svg-icon name="number_a"
                                            class="tag-icon" />竞价实例
                                    </div>
                                    <div class="tags" style="background: #F0DEFD;color: #AB33EB;"
                                        v-if="['daily', 'weekly', 'monthly'].includes(item?.Instance?.skuName)"><svg-icon
                                            name="icon_m_sub_c" class="tag-icon" />{{ payType[item?.Instance?.skuName] }}
                                    </div>

                                    <p class="page-txt">￥ <span class="col-money">{{ formatPrice(item) }}</span></p>
                                    <a-button type="link" :disabled="item?.Instance?.status !== 'running'"
                                        @click="goTensorboard(item)">Tensorboard</a-button>
                                    <a-button type="link" :disabled="item?.Instance?.status !== 'running'"
                                        @click="goJupyterLab(item)">JupyterLab</a-button>


                                    <a-dropdown v-if="item?.InstancePhysicalState?.toolsAttrsUrl?.custom?.length"
                                        :disabled="!(item?.InstancePhysicalState?.toolsAttrsUrl?.custom?.length) || item?.Instance?.status !== 'running'">
                                        <template #overlay>
                                            <a-menu>
                                                <a-menu-item
                                                    v-for="custom in item?.InstancePhysicalState?.toolsAttrsUrl?.custom">
                                                    <a :href="custom.url" target="_blank">自定义端口{{ custom.local_port }}</a>
                                                </a-menu-item>
                                            </a-menu>
                                        </template>

                                        <a-button type="link" @click.prevent>
                                            自定义端口
                                            <DownOutlined />
                                        </a-button>
                                    </a-dropdown>
                                </div>

                                <div class="flex">
                                    <a-button class="plain-button mr-8" @click="openLoginModal(item)"
                                        :disabled="item?.Instance?.isPending == 1 || item?.Instance?.status !== 'running'">
                                        <!-- <svg-icon name="icon_log_on" class="btn-icon" /> -->
                                        登录
                                    </a-button>
                                    <a-button class="plain-button mr-8" @click="openLogModal(item)"
                                        :disabled="item?.Instance?.isPending == 1 || item?.Instance?.status !== 'running'">
                                        <!-- <svg-icon name="icon_log" class="btn-icon" /> -->
                                        日志
                                    </a-button>
                                    <a-button class="plain-button mr-8"
                                        :disabled="item?.Instance?.isPending == 1 || item?.Instance?.status !== 'running'"
                                        @click="goMonitoring(item)">
                                        查看监控
                                    </a-button>


                                    <!-- <a-button class="plain-button mr-8" @click="openChooseSyncModal"
                                :disabled="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1">
                                <svg-icon name="icon_syn" class="btn-icon" />
                                数据同步
                            </a-button> -->

                                    <!-- 创建失败的实例不可操作 Instance  action:create  status:3  -->

                                    <a-dropdown :trigger="['click']">
                                        <template #overlay>
                                            <a-menu @click="(e) => onClickMenu(e, item)">
                                                <a-menu-item key="restart"
                                                    :disabled="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1 || (item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create')">
                                                    重启
                                                </a-menu-item>
                                                <a-menu-item key="noCardStart"
                                                    :disabled="item?.Instance?.status === 'running' || item?.Instance?.isPending == 1 || (item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create') || item?.Instance?.skuName == 'free'">
                                                    无卡启动
                                                </a-menu-item>
                                                <a-menu-item key="backupImage"
                                                    :disabled="item?.Instance?.status === 'running' || item?.Instance?.isPending == 1 || (item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create')">
                                                    备份镜像
                                                </a-menu-item>
                                                <a-menu-item key="restoreMirror"
                                                    :disabled="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1 || (item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create')">
                                                    通过镜像还原
                                                </a-menu-item>
                                                <a-menu-item key="update"
                                                    :disabled="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1 || (['daily', 'weekly', 'monthly', 'card_less'].includes(item?.Instance?.skuName)) || (item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create')">
                                                    <a-tooltip
                                                        v-if="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1 || (['daily', 'weekly', 'monthly', 'card_less'].includes(item?.Instance?.skuName))">
                                                        <template #title>预付费和无卡启动不能升降配</template>
                                                        升降配置
                                                    </a-tooltip>
                                                    <span v-else>升降配置</span>
                                                </a-menu-item>
                                                <a-menu-item key="changeRam"
                                                    :disabled="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1 || (item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create')">
                                                    扩缩容数据盘
                                                </a-menu-item>
                                                <a-menu-item key="changeBillingMethod"
                                                    :disabled="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1 || ['free', 'card_less'].includes(item?.Instance?.skuName) || (item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create')">
                                                    <a-tooltip
                                                        v-if="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1 || ['free', 'card_less'].includes(item?.Instance?.skuName)">
                                                        <template #title>无卡启动和机主机器不能变更计费方式</template>
                                                        变更计费方式
                                                    </a-tooltip>
                                                    <span v-else>变更计费方式</span>
                                                </a-menu-item>
                                                <!-- <a-menu-item key="cloneInstance">
                                            <a-button type="link"
                                                :disabled="item?.Machine?.type === '1' || item?.Instance?.isPending == 1">克隆实例</a-button>
                                        </a-menu-item> -->
                                                <a-menu-item key="reset_password"
                                                    :disabled="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1 || (item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create')">
                                                    重置密码
                                                </a-menu-item>
                                                <a-menu-item key="customizePort"
                                                    :disabled="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1 || !userInfo?.userItem?.idAuth || (item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create')">
                                                    <a-tooltip
                                                        v-if="item?.Instance?.status === 'running' && item?.Instance?.isPending !== 1 && !userInfo?.userItem?.idAuth">
                                                        <template #title>请先开启实名认证</template>
                                                        创建自定义端口
                                                    </a-tooltip>
                                                    <span v-else>创建自定义端口</span>
                                                </a-menu-item>
                                                <a-menu-item key="operatingLog">
                                                    操作记录
                                                </a-menu-item>
                                                <a-menu-item key="timedShutdown"
                                                    :disabled="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1 || !(['card_less', 'free', 'payg'].includes(item?.Instance?.skuName)) || (item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create')">
                                                    <a-tooltip
                                                        v-if="item?.Instance?.status !== 'running' || item?.Instance?.isPending == 1 || !(['card_less', 'free', 'payg'].includes(item?.Instance?.skuName))">
                                                        <template #title>预付费不能定时关机</template>
                                                        定时关机
                                                    </a-tooltip>
                                                    <span v-else>定时关机</span>
                                                </a-menu-item>
                                                <a-menu-item key="delete"
                                                    :disabled="item?.Instance?.status === 'running' || item?.Instance?.isPending == 1">
                                                    删除实例
                                                </a-menu-item>
                                            </a-menu>
                                        </template>

                                        <a-button>
                                            更多
                                            <DownOutlined />
                                        </a-button>
                                    </a-dropdown>

                                    <svg-icon
                                        v-if="item?.Instance?.status !== 'running' && item?.Instance?.isPending != 1 && !(item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create')"
                                        name="icon_start" class="opt-icon" @click="onStart(item)" />

                                    <svg-icon
                                        v-if="((item?.Instance?.status !== 'running' && item?.Instance?.isPending == 1) || (item?.Instance?.ioStatus == 3 && item?.Instance?.action == 'create'))"
                                        name="icon_start_disabled" class="opt-icon" />

                                    <svg-icon v-if="item?.Instance?.status === 'running' && item?.Instance?.isPending != 1"
                                        name="icon_suspend" class="opt-icon" @click="onPause(item)" />

                                    <svg-icon v-if="item?.Instance?.status === 'running' && item?.Instance?.isPending == 1"
                                        name="icon_stop_disabled" class="opt-icon" />
                                </div>

                            </div>
                        </a-card>

                        <a class="expand" @click="showMore(index)">
                            <template v-if="currentIndex.indexOf(index) != -1">
                                <UpOutlined />
                            </template>
                            <template v-else>
                                <DownOutlined />
                            </template>
                        </a>
                    </div>
                </div>
                <div class="no-data"
                    style="margin-top: 16px; display: flex;flex-direction: column;justify-content: center;align-items: center;"
                    v-else>
                    <svg-icon name="icon-no-data" style="width: 64px;height: 41px;"></svg-icon>
                    <div>暂无数据</div>
                </div>
            </div>
        </a-spin>

        <GpuDrawer v-model="docVisible" v-if="docVisible" :url="docurl"></GpuDrawer>

        <LoginModal v-model="loginVisible" v-if="loginVisible" :instance="instanceItem" />
        <!-- 实例日志 -->
        <LogModal v-model="logVisible" v-if="logVisible" :instance="instanceItem" />
        <!-- 操作记录 -->
        <OperatingLog v-model="operatingLogVisible" v-if="operatingLogVisible" :instance="instanceItem" />
        <!-- 数据同步 -->
        <ChooseSync v-model="chooseSyncVisible" v-if="chooseSyncVisible" :instance="instanceItem" />
        <!-- 开机重启 -->
        <ReStartInstance v-model="restartVisible" v-if="restartVisible" :instance="instanceItem" @handelOpt="handelOpt" />
        <!-- 重置密码 -->
        <ResetPwd v-model="resetPwdVisible" v-if="resetPwdVisible" :instance="instanceItem" @handelOpt="handelOpt" />
        <!-- 删除实例 -->
        <DeleteInstance v-model="deleteVisible" v-if="deleteVisible" :instance="instanceItem" @handelOpt="handelOpt" />
        <!-- 确认启动 -->
        <SureStart v-model="sureStartVisible" v-if="sureStartVisible" :instance="instanceItem" :fromTitle="fromTitle"
            @handelOpt="handelOpt" :setting="setTingList" @handelNoBalance="handelNoBalance" />
        <!-- 无卡启动 -->
        <NoCardStart v-model="noCardStartVisible" v-if="noCardStartVisible" :instance="instanceItem" :setting="setTingList"
            @handelOpt="handelOpt" @handelNoBalance="handelNoBalance" />
        <!-- 定时关机 -->
        <TimedShutdown v-model="timeDownVisible" v-if="timeDownVisible" :instance="instanceItem" @handelOpt="handelOpt" />
        <!-- 克隆实例 -->
        <CloneInstance v-model="cloneInstanceVisible" v-if="cloneInstanceVisible" :instance="instanceItem" />
        <!-- 扩缩容数据盘 -->
        <ChangeRam v-model="changeRamVisible" v-if="changeRamVisible" :instance="instanceItem" :setting="setTingList"
            @handelOpt="handelOpt" />
        <!-- 变更计费方式 -->
        <ChangeBillingMethod v-model="changeBillTypeVisible" v-if="changeBillTypeVisible" :instance="instanceItem"
            @handelOpt="handelOpt" @handelNoBalance="handelNoBalance" />
        <!-- 备份镜像 -->
        <BackupImage v-model="backupImageVisible" v-if="backupImageVisible" :instance="instanceItem"
            @handelOpt="handelOpt" />
        <!-- 选择要还原的镜像 -->
        <RestoreMirror v-model="restoreMirrorVisible" v-if="restoreMirrorVisible" :instance="instanceItem"
            @handelOpt="handelOpt" />
        <!-- 自定义端口 -->
        <CustomizePort v-model="customizePortVisible" v-if="customizePortVisible" :instance="instanceItem"
            @handelOpt="handelOpt" />
        <!-- 修改实例名称 -->
        <ChangeInstance v-model="changeInstanceVisible" v-if="changeInstanceVisible" :instance="instanceItem"
            @handelOpt="handelOpt" />

        <!-- 实例关机 -->
        <Shutdown v-model="shutdownVisible" v-if="shutdownVisible" :instance="instanceItem" @handelOpt="handelOpt">
        </Shutdown>

        <!-- 余额不足弹窗 -->
        <NoBalance v-model="rechargeVisible" v-if="rechargeVisible" :instanceFee="instanceFees"></NoBalance>

    </section>
</template>

<script setup name="instance">
import { ref } from 'vue'
import {
    UpOutlined,
    DownOutlined,
    CopyOutlined,
    CheckCircleFilled,
    InfoCircleFilled,
    QuestionCircleOutlined
} from '@ant-design/icons-vue';
import LoginModal from './components/loginModal.vue'
import LogModal from './components/instanceLog.vue'
import OperatingLog from './components/operatingLog.vue'
import ChooseSync from './components/chooseSync.vue'
import DeleteInstance from './components/deleteInstance.vue'
import ReStartInstance from './components/reStartInstance.vue'
import ResetPwd from './components/resetPwd.vue'
import SureStart from './components/sureStart.vue'
import NoCardStart from './components/noCardStart.vue'
import TimedShutdown from './components/timedShutdown.vue'
import CloneInstance from './components/cloneInstance.vue'
import ChangeRam from './components/changeRam.vue'
import ChangeBillingMethod from './components/changeBillingMethod.vue'
import BackupImage from './components/backupImage.vue'
import RestoreMirror from './components/restoreMirror.vue'
import CustomizePort from './components/customizePort.vue'
import ChangeInstance from './components/changeInstance.vue'
import Shutdown from './components/shutdown.vue'
import NoBalance from './components/noBalance.vue'
import { XsyMessage } from '@/libs/util.toast'
import { getInstanceList, handleInstance, getStatuslistApi } from 'api/modules/api.instance'
import { getSetting } from 'api/modules/api.common'
import { useRouter } from 'vue-router'
import { printSize } from '@/libs/util.common'
import { instanceStatusEnum, actionStatusEnum, selectDictLabel, selectDictColor, payType } from './enum.js'
import { useAction } from "./hooks/useAction";
import clipboard3 from "vue-clipboard3";
import { getNoticeListApi } from "@/api/modules/api.messages";
import { useNotice } from "@/hooks/sys/useNotice";
import { storeToRefs } from 'pinia'
import userInfoStore from '@/stores/userInfo.js'
import XsyModal from '@/components/common/XsyModal.vue';
const useUserInfoStore = userInfoStore()
const { userInfo } = storeToRefs(useUserInfoStore);

const {
    getNoticeList
} = useNotice(getNoticeListApi, showCb)

const loading = ref(true)

getNoticeList('instance')
const isShowNotice = ref(true)

// 单行的展开收起
const currentIndex = ref([])

function showMore(index) {
    if (currentIndex.value.indexOf(index) == -1) {
        currentIndex.value.push(index)
    } else {
        currentIndex.value = currentIndex.value.filter(item => item != index)
    }
}

// 通知消息
const noticeForm = ref({})
const open = ref(false)
function showCb(notice) {
    noticeForm.value = notice
    if (notice.location == 'pop') {
        open.value = true
    }
}

const handleOk = () => {
    open.value = false
}

const {
    doFetch,
    handleAction
} = useAction(getStatuslistApi, getListCb)

const router = useRouter()
const tableList = ref([]);
const form = ref({
    pn: 1,
    ps: 50
})

// 获取后台配置数据
const setTingList = ref([])
const getSet = () => {
    const params = {
        key: ['open_instance_storage_price', 'close_instance_storage_price']
    }
    getSetting(params).then(res => {
        if (res.code == 0) {
            setTingList.value = res.data.list || []
        }

    })
}

getSet()

// 请求列表
const getList = () => {
    const params = {
        ...form.value,
    }
    getInstanceList(params).then(res => {
        loading.value = false
        if (res.code == 0) {
            tableList.value = res.data.list || []
            handleStatus()
        }
    }).catch(() => {
        loading.value = false
    })
}

getList()

// 操作中的状态的时候去异步调用状态列表
const handleStatus = () => {
    let actionsIdList = []
    tableList.value.forEach(item => {
        if (item?.Instance?.isPending == 1) {
            actionsIdList.push(item?.Instance?.instanceId)
        }
    })

    // 请求hooks封装里面的请求
    doFetch(actionsIdList)
}

// 回调
function getListCb() {
    getList()
}

const onCreatInstance = e => {
    router.push('/' + e.key)
};

const instanceItem = ref({})

// 打开登录
const loginVisible = ref(false)
const openLoginModal = (item) => {
    instanceItem.value = item
    loginVisible.value = true
}

// 查看日志
const logVisible = ref(false)
const openLogModal = (item) => {
    instanceItem.value = item
    logVisible.value = true
}

// 查看监控
const goMonitoring = (item) => {
    router.push({ path: '/instanceMonitoring', query: { id: item.Instance.instanceId } })
}

// 打开操作日志
const operatingLogVisible = ref(false)

// 打开数据同步
const chooseSyncVisible = ref(false)
const openChooseSyncModal = () => {
    chooseSyncVisible.value = true
}
// 删除实例
const deleteVisible = ref(false)

// 开机的时候重启
const restartVisible = ref(false)

// 关机的时候开机
const sureStartVisible = ref(false)
const fromTitle = ref('确认开机')
const onStart = (item) => {
    instanceItem.value = item
    if (item.MachineSku.skuName == 'card_less') {
        noCardStartVisible.value = true
    } else {
        fromTitle.value = '确认开机'
        sureStartVisible.value = true
    }
}
// 无卡启动
const noCardStartVisible = ref(false)
// 备份镜像
const backupImageVisible = ref(false)
// 选择要还原的镜像
const restoreMirrorVisible = ref(false)
// 扩缩容数据盘
const changeRamVisible = ref(false)
// 变更计费方式
const changeBillTypeVisible = ref(false)
// 克隆实例
const cloneInstanceVisible = ref(false)
// 重置密码
const resetPwdVisible = ref(false)
// 创建自定义端口
const customizePortVisible = ref(false)

// 关机
const shutdownVisible = ref(false)
const onPause = (item) => {
    instanceItem.value = item
    shutdownVisible.value = true
}

// 定时关机
const timeDownVisible = ref(false)

// 下拉操作按钮
const onClickMenu = ({ key }, item) => {
    instanceItem.value = item
    switch (key) {
        case 'restart':
            restartVisible.value = true
            break;
        case 'noCardStart':
            noCardStartVisible.value = true
            break;
        case 'backupImage':
            backupImageVisible.value = true
            break;
        case 'restoreMirror':
            restoreMirrorVisible.value = true
            break;
        case 'update':
            fromTitle.value = '升降级配置'
            sureStartVisible.value = true
            break;
        case 'changeRam':
            changeRamVisible.value = true
            break;
        case 'changeBillingMethod':
            changeBillTypeVisible.value = true
            break;
        case 'cloneInstance':
            cloneInstanceVisible.value = true
            break;
        case 'reset_password':
            resetPwdVisible.value = true
            break;
        case 'customizePort':
            customizePortVisible.value = true
            break;
        case 'operatingLog':
            operatingLogVisible.value = true
            break;
        case 'timedShutdown':
            timeDownVisible.value = true
            break;
        case 'delete':
            deleteVisible.value = true
            break;
        default:

    }
}

// 修改实例名称
const changeInstanceVisible = ref(false)
const openChangeInstance = (item) => {
    instanceItem.value = item
    changeInstanceVisible.value = true
}

// 操作完成之后，准备调用异步请求
const handelOpt = (instanceId) => {
    handleAction(instanceId)
}

// 余额不足提示
const rechargeVisible = ref(false)
const instanceFees = ref(0)
const handelNoBalance = (fee) => {
    rechargeVisible.value = true
    instanceFees.value = fee
}

// 计算百分比
const formatPercentage = (val1, val2) => {
    if (val1 && val2) {
        return (val1 / val2) * 100
    } else {
        return 0
    }
}

// 根据百分比展示颜色
const getProgressColor = (val1, val2) => {
    if (!val1 && !val2) {
        return
    }
    let color = ''
    if (60 < ((val1 / val2) * 100) <= 80) {
        color = '#FAAD14'
    }
    if ((80 < (val1 / val2) * 100)) {
        color = '#FF2452'
    }
    return color
}

// 格式转换状态
const formatColr = (statusEnum, value) => {
    const type = selectDictColor(statusEnum, value)
    if (type == 'warning') {
        return 'warning'
    }

    return 'success'
}

// 跳转外连接
const goTensorboard = (item) => {
    const toolsAttrs = JSON.parse(item?.InstancePhysicalState?.toolsAttrs)
    const url = `http://${toolsAttrs.tensorboard.proxy_url}:${toolsAttrs.tensorboard.proxy_port}`
    window.open(url, '_blank')
}

// 跳转外连接
const goJupyterLab = (item) => {
    const toolsAttrs = JSON.parse(item?.InstancePhysicalState?.toolsAttrs)['jupyter notebook']
    const url = `http://${toolsAttrs.proxy_url}:${toolsAttrs.proxy_port}/lab?token=${toolsAttrs.token}`
    window.open(url, '_blank')
}

// 价格展示
const unitType = {
    'card_less': '小时',
    'free': '小时',
    'payg': '小时',
    'bidding': '小时',
    'daily': '天',
    'weekly': '周',
    'monthly': '月',

}
const formatPrice = (curItem) => {
    let price = ''
    let unit = ''
    price = curItem?.Order?.price
    unit = unitType[curItem?.Instance?.skuName]

    return price + '/' + unit
}

// 复制功能
const { toClipboard } = clipboard3();
const onCopy = async (key) => {
    try {
        await toClipboard(key.toString());
        XsyMessage.success("复制成功");
    } catch (e) {
        console.error(e);
    }
}

const docVisible = ref(false)
const docurl = ref('')
const openImageDocs = (key) => {
    docVisible.value = true
    docurl.value = window.location.origin + key
}

</script>

<style scoped lang="scss">
.head-notice {
    display: flex;
    align-items: center;
    color: #07F;
    font-size: 14px;
    font-style: normal;
    font-weight: 400;
    padding: 10px 24px 10px 10px;
    margin-bottom: 16px;
    background: #DCE8F6;
    border: 1px solid #07F;
    border-radius: 4px;
}

.page-wrap {
    height: 100%;

    .ant-spin-nested-loading {
        height: 100%;
    }
}

.icon-select {
    margin: 0 24px;

    :deep(.ant-select-selector) {
        padding-left: 30px;
    }

    :deep(.ant-select-selector)::before {
        position: absolute;
        left: 8px;
        top: 8px;
    }
}

.page-header {
    position: relative;

    :deep(.ant-space-item):hover::before {
        height: 2px;
        width: 180px;
        background: #223354;
        position: absolute;
        bottom: 0;
        content: '';
    }
}


.instanceType {
    :deep(.ant-select-selector)::before {
        content: url(@/assets/icons/svg/icon_instance_select1.svg);
    }
}

.region {
    :deep(.ant-select-selector)::before {
        content: url(@/assets/icons/svg/icon_instance_select2.svg);
    }
}

.stype {
    :deep(.ant-select-selector)::before {
        content: url(@/assets/icons/svg/icon_instance_select3.svg);
    }
}

.status {
    :deep(.ant-select-selector)::before {
        content: url(@/assets/icons/svg/icon_instance_select4.svg);
    }
}

.page-header {
    padding: 20px 15px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    box-shadow: 2px 2px 6px 0px rgba(0, 0, 0, 0.10);
    margin-bottom: 16px;
}

.card-title {
    padding: 16px 24px;
    background: #F3F5F7;
}

.flex {
    display: flex;
    align-items: center;
}

.list-expand {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .machine-date {
        display: flex;
        margin-left: auto;

        div {
            margin-left: 24px;
            color: #8A93A7;
            font-size: 14px;
            font-style: normal;
            font-weight: 400;
            line-height: normal;
        }
    }
}

.list-bottom {
    justify-content: space-between;
    margin-top: 24px;

    .ant-btn-primary,
    .ant-dropdown-trigger {
        margin-right: 8px;
    }

    .tags {
        min-width: 40px;
        height: 22px;
        line-height: 22px;
        padding: 2px 4px;
        font-size: 12px;
        border-radius: 4px;
        display: flex;
        align-items: center;
        margin-right: 8px;

        .tag-icon {
            width: 16px;
            height: 16px;
            margin-right: 3px;
        }
    }
}

.page-txt {
    color: #8A93A7;
    font-size: 14px;
    word-break: break-word;
}

.instance-cards {
    margin-bottom: 16px;
    position: relative;

    .expand {
        position: absolute;
        top: 24px;
        right: 24px;
        font-size: 14px;
        color: #999;
    }

    :deep(.ant-progress-text) {
        display: block !important;
        width: 100%;
        margin-top: 8px;
    }

    .ant-card {
        border-radius: 4px;
        box-shadow: 2px 2px 6px 0px rgba(0, 0, 0, 0.10);
    }

    .warning {
        border-radius: 2px;
        border: 0.5px solid #FFA39E;
        background: #FFF0F0;
        color: #FF2452;
        font-family: PingFang SC;
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
        padding: 5px;

    }

    .success {
        border-radius: 2px;
        border: 0.5px solid #B8EA8F;
        background: #F6FFEC;
        color: #53C41B;
        font-family: PingFang SC;
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
        padding: 5px;

    }
}

.plain-button {
    display: flex;
    align-items: center;
}

.plain-button:hover {
    .btn-icon {
        color: #ffffff;
    }
}

.btn-icon {
    width: 16px;
    height: 16px;
    margin-right: 8px;
}

.opt-icon {
    width: 32px;
    height: 32px;
    margin-left: 16px;
}
</style>

<style>
@media screen and (max-width: 1600px) {
    .page-wrap {
        .icon-select {
            margin: 0 12px;

            :deep(.ant-select-selector) {
                padding-left: 30px;
            }

            :deep(.ant-select-selector)::before {
                position: absolute;
                left: 8px;
                top: 8px;
            }
        }
    }

}

.page-wrap .ant-spin-container {
    height: 100%;
}
</style>

